package com.tigerlee.candle.spreadsheet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.tigerlee.candle.util.Constants;

import android.util.Log;

public class ArticleFeedParser {
	private XmlPullParserFactory mXmlPullParserFactory;
	
	
	private static final String TAG_TITLE = "gsx:title";
	private static final String TAG_NAME = "gsx:name";
	private static final String TAG_BODY = "gsx:body";
	

	public ArticleFeedParser() {
		// Initialize every array in FeedParedData
		ArticleFeedParedData.index = 0;
		ArticleFeedParedData.mTitleVector = new Vector<String>();
		ArticleFeedParedData.mNameVector = new Vector<String>();
		ArticleFeedParedData.mBodyVector = new Vector<String>();
	}
	public boolean getParedData(InputStream inputStream) {
		try {
			mXmlPullParserFactory = XmlPullParserFactory.newInstance();
			XmlPullParser mXmlPullParser = mXmlPullParserFactory.newPullParser();
			mXmlPullParser.setInput(inputStream, null);
			
			int mEventType = mXmlPullParser.getEventType();
			

			String tag = null;
			
			boolean isTitleTag = false;
			boolean isNameTag = false;
			boolean isBodyTag = false;
			
			while (mEventType != XmlPullParser.END_DOCUMENT) {
				switch (mEventType) {
				case XmlPullParser.START_TAG:
					tag = mXmlPullParser.getName();
					if(tag.compareTo(TAG_TITLE) == 0){
						ArticleFeedParedData.index++;
						isTitleTag = true;
						mEventType = mXmlPullParser.next();
					}
					else if (tag.compareTo(TAG_NAME) == 0) {
						isNameTag = true;
						mEventType = mXmlPullParser.next();
					}
					else if (tag.compareTo(TAG_BODY) == 0) {
						isBodyTag = true;
						mEventType = mXmlPullParser.next();
					} else {
						break;
					}
				case XmlPullParser.TEXT:
					try{
						if (isTitleTag) {
							ArticleFeedParedData.mTitleVector.add(mXmlPullParser.getText());						
						} else if(isNameTag){
							ArticleFeedParedData.mNameVector.add(mXmlPullParser.getText());
						} else if (isBodyTag) {
							ArticleFeedParedData.mBodyVector.add(mXmlPullParser.getText());												
						} else {
							break;
						}
					}catch (NullPointerException e) {
						e.printStackTrace();
					}
					
				case XmlPullParser.END_TAG:
					isTitleTag = false;
					isNameTag = false;
					isBodyTag = false;
					break;
				}
				mEventType = mXmlPullParser.next();
			}
		} catch (XmlPullParserException e) {
			if(Constants.LOG_VISIBLE) Log.d("XmlPullParserException", e.getMessage());
			return false;
			
		} catch (IOException e) {
			if(Constants.LOG_VISIBLE) Log.d("IOException", e.getMessage());
			return false;
		}
		if(ArticleFeedParedData.index != 0){
			return true;
		}else{
			return false;
		}
		
	}

}
